<template>
  <el-container>
    <el-header>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" @submit.prevent>
        <el-form-item label="组件名称">
          <el-input
            v-model="searchForm.componentName"
            placeholder="组件名称"
            @keyup.enter="onSearch"
          ></el-input>
        </el-form-item>
        <el-form-item label="应用编码">
          <el-input
            v-model="searchForm.appCode"
            placeholder="应用编码"
            @keyup.enter="onSearch"
          ></el-input>
        </el-form-item>
        <el-form-item label="组件类型">
          <el-select v-model="searchForm.componentType" placeholder="组件类型">
            <el-option
              v-for="item in compTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="default" @click="onReset">重置</el-button>
          <el-button type="default" @click="onAddComponent" icon="CirclePlus">
            新增组件</el-button
          >
        </el-form-item>
      </el-form>
    </el-header>
    <el-divider direction="horizontal"></el-divider>
    <el-main class="cus-main">
      <el-table :data="paginatedComponentList" style="width: 100%">
        <el-table-column
          prop="id"
          label="ID"
          v-if="false"
        ></el-table-column>
        <el-table-column
          prop="appCode"
          label="应用编码"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="组件名称"
        ></el-table-column>
        <el-table-column
          prop="type"
          label="组件类型"
        >
        <template #default="scope">
              {{
                compTypes.find((c) => c.value === scope.row.type).label
              }}
          </template>      
      </el-table-column>
        <el-table-column
          prop="description"
          label="组件描述"
        ></el-table-column>
        <el-table-column label="操作" >
          <template #default="scope">
            <el-button link type="primary" @click="onEdit(scope.row)">编辑</el-button>
            <el-button link type="primary" @click="onDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="listTotal"
      >
      </el-pagination>
    </el-main>
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '修改组件' : '新增组件'"
      width="40%"
      header-class="dialog-custom-header"
    >
    <el-divider direction="horizontal" style="width: 95%"></el-divider>

      <el-form :model="newComponentForm" label-width="70px">
        <el-form-item label="应用编码">
          <el-input v-model="newComponentForm.appCode"></el-input>
        </el-form-item>
        <el-form-item label="组件名称">
          <el-input v-model="newComponentForm.name"></el-input>
        </el-form-item>
        <el-form-item label="组件类型">
          <el-select v-model="newComponentForm.type" placeholder="组件类型">
            <el-option
              v-for="item in compTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
            <!-- 其他类型 -->
          </el-select>
        </el-form-item>
        <el-form-item label="组件描述">
          <el-input v-model="newComponentForm.description"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { get, post, put, del } from "@/utils/request";
const compTypes = ref([]);
const dialogVisible = ref(false);
const isEdit = ref(false); // 是否为修改模式
const currentEditId = ref(null); // 当前编辑的组件ID
const searchForm = reactive({
  componentName: null,
  appCode: null,
  componentType: null,
});
const newComponentForm = reactive({
  appCode: "",
  name: "",
  type: "",
  description: "",
});
const componentList = ref([
  // 其他组件数据...
]);
const currentPage = ref(1);
const pageSize = ref(10);
const listTotal = ref(0);
const paginatedComponentList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return componentList.value.slice(start, end);
});

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  onSearch();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  onSearch();
};

const onSearch = () => {
  let params = {
    appCode: searchForm.appCode,
    name: searchForm.componentName,
    type: searchForm.componentType,
    page: currentPage.value,
    size: pageSize.value,
  };
  get("/apm/comps", params)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        componentList.value = res.data.data.data;
        listTotal.value = res.data.data.total;
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

const onReset = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = null;
  });
};

const onAddComponent = () => {
  isEdit.value = false;
  Object.keys(newComponentForm).forEach((key) => {
    newComponentForm[key] = null;
  });
  dialogVisible.value = true;
};

const onEdit = (row) => {
  dialogVisible.value = true;
  isEdit.value = true;
  currentEditId.value = row.id;
  Object.assign(newComponentForm, row);
};

const onDelete = (row) => {
  del("/apm/comps/" + row.id)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        componentList.value = componentList.value.filter(
          (item) => item.id !== row.id
        );
        ElMessage.success("删除成功");
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

const onSubmit = async () => {
  let succ = false;
  if (isEdit.value) {
    // 修改组件逻辑
    const index = componentList.value.findIndex(
      (item) => item.id === currentEditId.value
    );
    if (index !== -1) {
      componentList.value[index] = {
        ...newComponentForm,
        id: currentEditId.value,
      };
    }
    let payload = {
      appCode: newComponentForm.appCode,
      name: newComponentForm.name,
      type: newComponentForm.type,
      description: newComponentForm.description,
    };
    await put("/apm/comps/" + currentEditId.value, payload)
      .then((res) => {
        // console.log("搜索结果:", res);
        if (res.data.code === 0) {
          succ = true;
          ElMessage.success("更新成功");
        } else if (res.data.code === 401) {
          sessionStorage.clear();
          window.location.assign("/login");
        } else {
          ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
        }
      })
      .catch((e) => {
        ElMessage.error(e.message);
      });
  } else {
    // 新增组件逻辑
    let payload = {
      appCode: newComponentForm.appCode,
      name: newComponentForm.name,
      type: newComponentForm.type,
      description: newComponentForm.description,
    };
    await post("/apm/comps", payload)
      .then((res) => {
        if (res.data.code === 0) {
          componentList.value.push({
            ...newComponentForm,
            id: res.data.data.id,
          });
          succ = true;
          ElMessage.success("新增成功");
        } else if (res.data.code === 401) {
          sessionStorage.clear();
          window.location.assign("/login");
        } else {
          ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
        }
      })
      .catch((e) => {
        ElMessage.error(e.message);
      });
  }
  if (succ) {
    dialogVisible.value = false;
  }
};

onMounted(async() => {
  // 初始化字典
  await get("/apm/comps/types")
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        compTypes.value = res.data.data.data;
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
  onSearch();
});
</script>

